package custom
import (
"sort"
"strings"
"github.com/K-Phoen/sdk"
)
const All = "$__all"
type Option func (constant *Custom )
type ValuesMap map [string ]string
func (values ValuesMap ) asQuery () string {
valuesList := make ([]string , 0 , len (values ))
for _ , value := range values {
valuesList = append (valuesList , value )
}
sort .Strings (valuesList )
return strings .Join (valuesList , "," )
}
func (values ValuesMap ) labelFor (value string ) *sdk .StringSliceString {
for label , val := range values {
if val == value {
return &sdk .StringSliceString {Value : []string {label }, Valid : true }
}
}
return &sdk .StringSliceString {Value : []string {value }, Valid : true }
}
type Custom struct {
Builder sdk .TemplateVar
values ValuesMap
}
func New (name string , options ...Option ) *Custom {
custom := &Custom {Builder : sdk .TemplateVar {
Name : name ,
Label : name ,
Type : "custom" ,
Options : []sdk .Option {},
}}
for _ , opt := range options {
opt (custom )
}
return custom
}
func Values (values ValuesMap ) Option {
return func (custom *Custom ) {
for label , value := range values {
custom .Builder .Options = append (custom .Builder .Options , sdk .Option {
Text : label ,
Value : value ,
})
}
custom .values = values
custom .Builder .Query = values .asQuery ()
}
}
func Default (value string ) Option {
return func (custom *Custom ) {
custom .Builder .Current = sdk .Current {
Text : custom .values .labelFor (value ),
Value : value ,
}
}
}
func Label (label string ) Option {
return func (custom *Custom ) {
custom .Builder .Label = label
}
}
func HideLabel () Option {
return func (custom *Custom ) {
custom .Builder .Hide = 1
}
}
func Hide () Option {
return func (custom *Custom ) {
custom .Builder .Hide = 2
}
}
func Multiple () Option {
return func (custom *Custom ) {
custom .Builder .Multi = true
}
}
func IncludeAll () Option {
return func (custom *Custom ) {
custom .Builder .IncludeAll = true
custom .Builder .Options = append (custom .Builder .Options , sdk .Option {
Text : "All" ,
Value : All ,
})
}
}
func DefaultAll () Option {
return func (custom *Custom ) {
custom .Builder .Current = sdk .Current {Text : &sdk .StringSliceString {Value : []string {"All" }, Valid : true }, Value : All }
}
}
func AllValue (value string ) Option {
return func (custom *Custom ) {
custom .Builder .AllValue = value
}
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .